﻿using MediatR;
using Sowrk03_28.Repository;
using Swork03_28.Api.Application.Commands.FarmedCommand;
using Swork03_28.Domain.TraceableInfos;
using Swork03_28.Services.Interface;

namespace Swork03_28.Api.Application.CommandHandlers.FarmedHandler
{
    public class VaccineCreateCertificateImgCommandHandler : IRequestHandler<VaccineCreateCertificateImgCommand, int>
    {
        private readonly IRepository<Vaccine> repository;
        private readonly IFarmedService farmedService;

        public VaccineCreateCertificateImgCommandHandler(IRepository<Vaccine> repository, IFarmedService farmedService)
        {
            this.repository = repository;
            this.farmedService = farmedService;
        }

        public async Task<int> Handle(VaccineCreateCertificateImgCommand request, CancellationToken cancellationToken)
        {
            var count = 0;
            var info = await farmedService.GetValues(x => x.BatchId == request.BatchId);
            var res = info.FirstOrDefault();
            if (res != null)
            {
                res.Certificate = (res.Certificate + "," + request.Imgs).TrimStart(",".ToCharArray()).TrimEnd(",".ToCharArray());
                count += await farmedService.UpdateAsync(res);
            }
            else
            {
                var imgs = ("," + request.Imgs).TrimStart(",".ToCharArray()).TrimEnd(",".ToCharArray());
                count += await farmedService.CreateAsync(new Farmed()
                {
                    BatchId = request.BatchId,
                    Brand = null,
                    Breed = null,
                    Certificate = imgs,
                    FarmId = 0,
                    Feeding = 0,
                    Principal = null,
                    PublicationDate = null,
                    Source = null
                });
            }
            return count;
        }
    }
}
